home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5661 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: What's better & why
  5. Date: Tue, 20 Feb 1996 11:33:11 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <31299557.3861@cmt.lpr.mail.carel.fi>
  8. References: <31297C5A.E6C@connix.com>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6a (WinNT; I)
  14.  
  15. Scott Hawley wrote:
  16. > I was just curious what you all though about the following code.
  17. > Please tell me what is better (faster/Smaller) and why. Or does it make
  18. > any difference at all. I just though about this while I was programming
  19. > today?
  20. > example 1:
  21. >                 val = 1;
  22. >                 if( what ever...)val = 0;
  23.  
  24. This might be compiled to (expressed in Assembly):
  25.  
  26.     mov    [val],1
  27.     ; perform comparison
  28.     jz    Skip    ; or the proper flag (jnz, jc...)
  29.     mov    [val],0
  30. Skip:    ; other code
  31.  
  32. > or
  33. > example 2:
  34. >                 if( what ever... )val = 0;
  35. >                 else val = 1;
  36.  
  37. This might become:
  38.  
  39.     ; perform comparison
  40.     jz    Skip    ; or the proper flag
  41.     mov    [val],0
  42.     jmp    Skip2
  43. Skip:    mov    [val],1
  44. Skip2:    ; other code
  45.  
  46. > amy remarks?
  47.  
  48. So, it seems the latter produces more code. However, a smart compiler would probably 
  49. optimize it to be something like the first example. In any case, I normally use:
  50.  
  51.     val = (what ever) ? 0 : 1;
  52.  
  53. Which you'd prefer, that's up to you. An optimizing compiler could even produce code 
  54. like this:
  55.  
  56.     mov    [val],0
  57.     ; perform comparison
  58.     jnz    Skip    ; oppose result from the ones above, val left as 0
  59.     inc    [val]    ; val = val + 1, ie. 1
  60. Skip:    ; other code
  61.  
  62. which would be better than the two examples above. (The examples assume use of an 
  63. Intel-based compiler.)
  64.  
  65. Later,
  66.  AriL
  67. -- 
  68. All my opinions are mine and mine alone.
  69.